package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Customer;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import persistence.CheckAndRegister;
import persistence.CustomerDao;

/**
 * Servlet implementation class UserRegister
 */
//@WebServlet("/UserRegister")
public class UserRegister extends MyHttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) {
		Customer user = new Customer();

		Document xmlDoc = getDocument(request);
		NodeList userNodeList = xmlDoc.getElementsByTagName("user").item(0).getChildNodes();
		user.setName(userNodeList.item(0).getFirstChild().getNodeValue());
		user.setPassword(userNodeList.item(1).getFirstChild().getNodeValue());
		user.setPhone(userNodeList.item(2).getFirstChild().getNodeValue());
		user.setEmail(userNodeList.item(3).getFirstChild().getNodeValue());
		user.setGender(userNodeList.item(4).getFirstChild().getNodeValue().equals("on")?'m':'f');
		user.setDescription(userNodeList.item(5).getFirstChild().getNodeValue());
		
		String imagePath = userNodeList.item(6).getFirstChild().getNodeValue();

		
		
		String[] buffer = imagePath.split("\\\\\\\\");
		StringBuffer strBuf = new StringBuffer(buffer[0]);
		for (int i = 1; i < buffer.length; i++) {
			strBuf.append("\\");
			strBuf.append(buffer[i]);
		}
		user.setStatus(strBuf.toString());
//		CustomerDao.save(user, strBuf.toString());
		
		CheckAndRegister.register(user);

		try {
			printWriter = response.getWriter();
			response.setContentType("application/xml");
			addTag("result", "success");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	
}